package com.zenith.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zenith.user.mapper.RoleMapper;
import com.zenith.user.po.domain.Role;
import com.zenith.user.po.domain.RolePermission;
import com.zenith.user.po.domain.UserRole;
import com.zenith.user.po.dto.RoleDTO;
import com.zenith.user.service.RolePermissionService;
import com.zenith.user.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenith.common.result.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenith.user.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 角色 业务实现
 *
 * @author makejava
 * @since 2025-08-15
 */
@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public PageResult<Role> getRolePage(RoleDTO query) {
        // 创建分页对象
        Page<Role> page = new Page<>(query.getPageNum() != null ? query.getPageNum() : 1, 
                                   query.getPageSize() != null ? query.getPageSize() : 10);
        // 执行分页查询
        Page<Role> pageResult = lambdaQuery().page(page);
        // 封装返回结果
        return PageResult.ofPage(page.getCurrent(), page.getSize(), pageResult.getTotal(), pageResult.getRecords());
    }

    @Override
    public boolean createRole(RoleDTO roleDTO) {
        log.info("创建角色: {}", roleDTO.getRoleName());
        try {
            Role role = new Role();
            role.setRoleName(roleDTO.getRoleName());
            role.setDescription(roleDTO.getDescription());
            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());
            role.setIsDelete(0);
            return save(role);
        } catch (Exception e) {
            log.error("创建角色失败", e);
            throw new RuntimeException("创建角色失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateRole(RoleDTO roleDTO) {
        log.info("更新角色: ID={}", roleDTO.getId());
        try {
            Role role = getById(roleDTO.getId());
            if (role == null) {
                throw new RuntimeException("角色不存在");
            }
            
            // 更新角色信息
            if (StringUtils.hasText(roleDTO.getRoleName())) {
                role.setRoleName(roleDTO.getRoleName());
            }
            if (StringUtils.hasText(roleDTO.getDescription())) {
                role.setDescription(roleDTO.getDescription());
            }
            role.setUpdateTime(LocalDateTime.now());
            
            return updateById(role);
        } catch (Exception e) {
            log.error("更新角色失败", e);
            throw new RuntimeException("更新角色失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteRole(Long id) {
        log.info("删除角色: ID={}", id);
        try {
            Role role = getById(id);
            if (role == null) {
                throw new RuntimeException("角色不存在");
            }

            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", role.getId());
            List<UserRole> list = userRoleService.list(queryWrapper);
            if (!list.isEmpty()) {
                throw new RuntimeException("角色被用户使用，不允许删除");
            }
            QueryWrapper<UserRole> userQueryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", role.getId());
            List<UserRole> userList = userRoleService.list(userQueryWrapper);
            if (!list.isEmpty()) {
                throw new RuntimeException("角色被用户使用，不允许删除");
            }
            return removeById(id);
        } catch (Exception e) {
            log.error("删除角色失败", e);
            throw new RuntimeException("删除角色失败: " + e.getMessage());
        }
    }

    /**
     * 批量为角色分配权限
     *
     * @param roleId 角色ID
     * @param permissionIds 权限ID列表
     * @return 是否分配成功
     */
    @Override
    public boolean batchAssignPermissions(Long roleId, List<Long> permissionIds) {
        log.info("批量分配角色权限: roleId={}, permissionIds={}", roleId, permissionIds);
        try {
            // 检查角色是否存在
            Role role = getById(roleId);
            if (role == null) {
                throw new RuntimeException("角色不存在");
            }

            // 1. 删除原有的角色权限关联
            QueryWrapper<RolePermission> queryRoleIdWrapper = new QueryWrapper<>();
            queryRoleIdWrapper.eq("role_id", roleId);
            boolean remove = rolePermissionService.remove(queryRoleIdWrapper);
            // 2. 插入新的角色权限关联
            if (remove){
                //批量插入角色权限关联
                for (Long permissionId : permissionIds) {
                    QueryWrapper<RolePermission> queryPermissionIdWrapper = new QueryWrapper<>();
                    queryPermissionIdWrapper.eq("permission_id", permissionId);
                    queryPermissionIdWrapper.eq("role_id", roleId);
                    if (!rolePermissionService.exists(queryPermissionIdWrapper)) {
                        RolePermission rolePermission = new RolePermission();
                        rolePermission.setRoleId(roleId);
                        rolePermission.setPermissionId(permissionId);
                        rolePermissionService.save(rolePermission);
                    }
                }

            }
            
            log.info("角色权限批量分配成功: roleId={}", roleId);
            return true;
        } catch (Exception e) {
            log.error("批量分配角色权限失败", e);
            throw new RuntimeException("批量分配角色权限失败: " + e.getMessage());
        }
    }
}